﻿package net.imonair.core.contacts {
	import flash.events.EventDispatcher;
	import net.imonair.core.connectors.IIMConnector;
	import net.imonair.core.contacts.IIMContact;
	import net.imonair.core.events.IMContactListEvent;
	public class IMContactList extends EventDispatcher {
		private var _contacts:Object = {};
		private var _length:uint = 0;
		private var _connector:IIMConnector;
		/**
		 * Creates a new contact list instance.
		 * @param connector A related connector.
		 */
		public function IMContactList(connector:IIMConnector) {
			this._connector = connector;
		}
		/**
		 * Provides an array containing all contacts on that list.
		 */
		public function get contacts():Array {
			var array:Array = [];
			for each (var value:IIMContact in this._contacts) array.push(value);
			return array;
		}
		/**
		 * Provides amount of contacts on list.
		 */
		public function get length():uint {
			return this._length;
		}
		/**
		 * Adds a new contact onto the list.
		 * @param contact A contact to be added.
		 * @return A value representing successful addition of contact. Value <code>true</code> means success, value <code>false</code> means that contact is already on list and was not added.
		 */
		public function addContact(contact:IIMContact):Boolean {
			trace(contact)
			if (this._contacts[contact.id]) return false;
			this._contacts[contact.id] = contact;
			this._length++;
			trace(this._contacts[contact.id])
			this._connector.dispatchEvent(new IMContactListEvent(IMContactListEvent.ADDED, this, contact));
			return true;
		}
		/**
		 * Removes a contact from list.
		 * @param contact A contact to be deleted.
		 * @return A value representing successful deletion of contact. Value <code>true</code> means success, value <code>false</code> means that contact didn't exist on list and was not deleted.
		 */
		public function removeContact(contact:IIMContact):Boolean {
			for (var id:String in this._contacts) if (this._contacts[id] == contact) {
				removeContactById(id);
				return true;
			}
			return false;
		}
		public function removeContactById(value:String):void {
			var contact:IIMContact = this._contacts[value];
			delete this._contacts[value];
			this._length--;
			this._connector.dispatchEvent(new IMContactListEvent(IMContactListEvent.REMOVED, this, contact));
		}
		public function getContactById(id:String):IIMContact {
			return this._contacts[id];
		}
	}
}